import { Module, forwardRef } from '@nestjs/common';
import { EmailService } from './email.service';
import { EmailController } from './email.controller';
import { MailerModule } from '@nestjs-modules/mailer';
import { ConfigurationModule } from '../configuration/configuration.module';
import { ConfigurationService } from '../configuration/configuration.service';

@Module({
  imports: [
    forwardRef(() => ConfigurationModule),
    MailerModule.forRootAsync({
      imports: [forwardRef(() => ConfigurationModule)],
      useFactory: async (configurationService: ConfigurationService) => {
        try {
          // 获取活跃的邮件配置
          const emailConfig = await configurationService.getActiveEmailConfig();
          
          // 如果获取到邮件配置，使用动态配置
          if (emailConfig && emailConfig.emailHost && emailConfig.emailUser && emailConfig.emailPassword) {
            return {
              transport: {
                host: emailConfig.emailHost,
                port: emailConfig.emailPort || 587,
                secure: emailConfig.emailSecure || false,
                auth: {
                  user: emailConfig.emailUser,
                  pass: emailConfig.emailPassword
                }
              },
              defaults: {
                from: emailConfig.emailUser
              }
            };
          }
          
          // 如果没有配置邮件信息，使用默认配置
          return {
            transport: {
              host: "smtp.qq.com",
              port: 587,
              secure: false,
              auth: {
                user: '2735332396@qq.com',
                pass: 'rkmxxazafyebdgdb'
              }
            }
          };
        } catch (error) {
          console.warn('获取邮件配置失败，使用默认配置:', error.message);
          // 发生错误时使用默认配置
          return {
            transport: {
              host: "smtp.qq.com",
              port: 587,
              secure: false,
              auth: {
                user: '2735332396@qq.com',
                pass: 'rkmxxazafyebdgdb'
              }
            }
          };
        }
      },
      inject: [ConfigurationService]
    })
  ],
  controllers: [EmailController],
  providers: [EmailService],
  exports: [EmailService]
})
export class EmailModule {}
